package com.twu.biblioteca;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;

public class BibliotecaApp {

    private final BookCollection bookCollection;
    private final MovieCollection movieCollection;
    private final UserCollection userCollection;
    private User currentUser;

    public BibliotecaApp(BookCollection bookCollection, MovieCollection movieCollection, UserCollection userCollection, User currentUser) {
        this.bookCollection = bookCollection;
        this.movieCollection = movieCollection;
        this.userCollection = userCollection;
        this.currentUser = currentUser;
    }

    private static Menu find(String input) {
        for (Menu m : Menu.values()) {
            if (m.matches(input)) {
                return m;
            }
        }
        return Menu.INVAlID;
    }

    public void run(PrintStream printStream, InputStream inputStream) {

        printStream.println("Welcome to Biblioteca");
        printMenuList(printStream);
        Scanner scanner = new Scanner(inputStream).useDelimiter("\n");

        while (scanner.hasNext()) {

            String input = scanner.next();
            ViewState viewState = find(input).execute(scanner, printStream, bookCollection, movieCollection, userCollection, currentUser);
            if (!viewState.keepProcessing) {
                return;
            }
            currentUser = viewState.currentUser;
            printMenuList(printStream);
        }
    }

    private void printMenuList(PrintStream printStream) {
        for (Menu m : Menu.values()) {
            printStream.print(m);
        }
    }
}
